<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh">
<head>
  <meta charset="UTF-8">
  <title th:text="${course.couName} + ' - 课程详情 - 企业培训平台'">课程详情 - 企业培训平台</title>
  <link rel="stylesheet" th:href="@{/css/style.css}">
  <style>
    /* General layout for the detail page */
    /* ... 您现有的CSS样式 ... */

    /* 新增的模态框CSS样式 (已存在，无需更改) */
    .modal {
      display: none; /* 默认隐藏 */
      position: fixed; /* 固定定位 */
      z-index: 1000; /* 确保在最上层 */
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto; /* 允许滚动 */
      background-color: rgba(0,0,0,0.8); /* 半透明黑色背景 */
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
    }

    .modal-content {
      background-color: #fefefe;
      margin: auto; /* 自动外边距用于居中 */
      padding: 20px;
      border: 1px solid #888;
      width: 80%; /* 模态框宽度 */
      max-width: 900px; /* 最大宽度 */
      box-shadow: 0 5px 15px rgba(0,0,0,0.3);
      border-radius: 8px;
      position: relative; /* 相对定位，用于关闭按钮 */
      animation: fadeIn 0.3s; /* 淡入动画 */
    }

    .modal-content video {
      width: 100%; /* 视频宽度占满模态框 */
      height: auto;
      display: block; /* 移除图片底部空白 */
    }

    .close-button {
      color: #aaa;
      position: absolute;
      top: 10px;
      right: 20px;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
      transition: 0.3s;
      z-index: 1001; /* 新增或修改此行，确保高于模态框的z-index */
    }

    .close-button:hover,
    .close-button:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-20px); }
      to { opacity: 1; transform: translateY(0); }
    }
    /* 响应式调整 */
    @media (max-width: 768px) {
      .modal-content {
        width: 95%;
        padding: 15px;
      }
      .close-button {
        font-size: 24px;
        top: 5px;
        right: 15px;
      }
    }
    .course-detail-container {
      display: flex;
      flex-wrap: wrap; /* Allow wrapping on smaller screens */
      gap: 20px;
      margin-top: 20px;
    }

    .course-info-section {
      flex: 2; /* Takes more space */
      min-width: 300px; /* Minimum width for this section */
      background-color: #fff;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .course-image-section {
      flex: 1; /* Takes less space */
      min-width: 250px; /* Minimum width for this section */
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      text-align: center;
    }

    .course-image-section img {
      max-width: 100%;
      height: auto;
      border-radius: 8px;
      margin-bottom: 15px;
    }

    .course-info-section h2 {
      color: #333;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.8em;
    }

    .course-info-section p {
      margin-bottom: 8px;
      color: #555;
      line-height: 1.6;
    }

    .course-info-section strong {
      color: #333;
    }

    .course-intro {
      background-color: #f9f9f9;
      padding: 15px;
      border-radius: 6px;
      border-left: 4px solid #007bff;
      margin-top: 20px;
    }

    /* Chapter List Styles */
    .chapters-section {
      flex-basis: 100%; /* Takes full width below info sections */
      background-color: #fff;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      margin-top: 20px;
    }

    .chapters-section h2 {
      color: #333;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.5em;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chapters-section table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 15px;
    }

    .chapters-section th, .chapters-section td {
      border: 1px solid #ddd;
      padding: 10px;
      text-align: left;
    }

    .chapters-section th {
      background-color: #f2f2f2;
      font-weight: bold;
      color: #333;
    }

    .chapters-section tr:nth-child(even) {
      background-color: #f9f9f9;
    }

    .chapters-section tr:hover {
      background-color: #e9e9e9;
    }

    .chapters-section .actions-column a,
    .chapters-section .actions-column button {
      margin-right: 5px;
    }

    .no-chapters-message {
      text-align: center;
      margin-top: 20px;
      font-size: 1.1em;
      color: #666;
    }

    /* Modal Styles (for chapter edit) */
    .modal-content .form-group {
      margin-bottom: 15px;
    }

    .modal-content .form-group label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }

    .modal-content .form-group input[type="text"],
    .modal-content .form-group input[type="number"] {
      width: calc(100% - 16px); /* Account for padding */
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    .modal-content .form-actions {
      text-align: right;
      margin-top: 20px;
    }

    .modal-content .form-actions button {
      margin-left: 10px;
    }

    /* NEW: Comments Section Styles */
    .comments-section {
      background-color: #fff;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      margin-top: 20px;
    }
    .comments-section h2 {
      color: #333;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.5em;
      border-bottom: 2px solid #eee;
      padding-bottom: 10px;
    }
    .comment-item {
      border: 1px solid #e9ecef;
      background-color: #fdfdfd;
      padding: 15px;
      margin-bottom: 15px;
      border-radius: 6px;
    }
    .comment-item .comment-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      font-size: 0.95em;
      color: #777;
    }
    .comment-item .comment-meta strong {
      color: #333;
    }
    .comment-item .comment-content {
      color: #444;
      line-height: 1.5;
      margin-bottom: 10px;
    }
    .comment-item .comment-rating {
      font-weight: bold;
      color: #ffc107; /* Star color */
    }
    .no-comments-message {
      padding: 20px;
      text-align: center;
      color: #6c757d;
      background-color: #e9ecef;
      border-radius: 8px;
      margin-top: 10px;
    }

    /* NEW: Comment Form Styles */
    .comment-form-section {
      background-color: #fff;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      margin-top: 20px;
    }
    .comment-form-section h2 {
      color: #333;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.5em;
      border-bottom: 2px solid #eee;
      padding-bottom: 10px;
    }
    .comment-form .form-group {
      margin-bottom: 15px;
    }
    .comment-form label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #333;
    }
    .comment-form textarea {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      min-height: 100px;
      box-sizing: border-box; /* Include padding in element's total width and height */
    }
    .comment-form select {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      box-sizing: border-box;
    }
    .comment-form .btn-primary {
      background-color: #007bff;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1em;
      transition: background-color 0.3s ease;
    }
    .comment-form .btn-primary:hover {
      background-color: #0056b3;
    }

    /* Actions for Like/Collect/Enroll */
    .course-actions {
      margin-top: 20px;
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
    .course-actions button {
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1em;
      transition: background-color 0.3s ease;
    }
    .course-actions .btn-like {
      background-color: #28a745; /* Green */
      color: white;
    }
    .course-actions .btn-like:hover {
      background-color: #218838;
    }
    .course-actions .btn-collect {
      background-color: #007bff; /* Blue */
      color: white;
    }
    .course-actions .btn-collect:hover {
      background-color: #0056b3;
    }
    .course-actions .btn-collected {
      background-color: #6c757d; /* Grey when collected */
      color: white;
      cursor: not-allowed;
    }

    /* Offline Practice Section */
    .offline-practices-section {
      background-color: #fff;
      padding: 25px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      margin-top: 20px;
    }
    .offline-practices-section h2 {
      color: #333;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.5em;
      border-bottom: 2px solid #eee;
      padding-bottom: 10px;
    }
    .offline-practice-item {
      border: 1px solid #e9ecef;
      background-color: #fdfdfd;
      padding: 15px;
      margin-bottom: 15px;
      border-radius: 6px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap; /* Allow wrapping */
    }
    .offline-practice-item div {
      flex: 1;
      min-width: 200px; /* Adjust as needed */
      margin-bottom: 10px; /* Space out items on wrap */
    }
    .offline-practice-item .btn-enroll {
      background-color: #ffc107; /* Yellowish */
      color: #333;
      padding: 8px 15px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;
      margin-top: 10px; /* Add margin for wrapped button */
    }
    .offline-practice-item .btn-enroll:hover {
      background-color: #e0a800;
    }
    .no-offline-practices-message {
      padding: 20px;
      text-align: center;
      color: #6c757d;
      background-color: #e9ecef;
      border-radius: 8px;
      margin-top: 10px;
    }

    /* Enroll Modal specific styles */
    #enrollModal .modal-content {
      max-width: 600px; /* Smaller width for enrollment form */
    }
    #enrollModal form label {
      margin-top: 10px;
    }
    #enrollModal form input,
    #enrollModal form textarea {
      width: calc(100% - 22px); /* Adjust for padding and border */
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-bottom: 10px;
    }
    #enrollModal form button {
      margin-right: 10px;
    }


    /* Responsive adjustments */
    @media (max-width: 768px) {
      .course-detail-container {
        flex-direction: column;
      }
      .course-info-section, .course-image-section {
        min-width: unset; /* Remove min-width for full flexibility */
        flex: none; /* Reset flex to default */
        width: 100%; /* Take full width */
      }
      .modal-content {
        width: 95%;
        padding: 20px;
      }
      .course-actions button {
        width: 100%; /* Full width buttons on small screens */
        margin-bottom: 10px;
      }
    }
    /* 新增：教师/回复相关的样式 */
    .teacher-reply-box {
      background-color: #f0f8ff; /* 淡蓝色背景 */
      border-left: 4px solid #4a90e2; /* 蓝色强调边框 */
      padding: 15px;
      margin-top: 15px;
      margin-left: 20px; /* 缩进以表示层级 */
      border-radius: 5px;
    }
    .teacher-reply-box strong { color: #4a90e2; }

    .reply-to-teacher-form {
      margin-top: 10px;
      margin-left: 20px; /* 与回复对齐 */
    }
    .reply-to-teacher-form textarea {
      width: 100%;
      min-height: 60px;
    }

  </style>
</head>
<div th:replace="~{fragments/header :: header}"></div>

<div class="main-content">
  <div class="container">
    <h1 class="page-title" th:text="${course.couName} + ' 课程详情'">课程详情</h1>

    <div th:if="${successMessage}" class="alert alert-success">
      <p th:text="${successMessage}"></p>
    </div>
    <div th:if="${errorMessage}" class="alert alert-danger">
      <p th:text="${errorMessage}"></p>
    </div>

    <div class="course-detail-container">
      <div class="course-info-section">
        <h2>课程信息</h2>
        <p><strong>课程名称:</strong> <span id="courseName" th:text="${course.couName}"></span></p>
        <p><strong>课程ID:</strong> <span id="courseId" th:text="${course.id}"></span></p>
        <p><strong>讲师ID:</strong> <span th:text="${course.teaId}"></span></p>
        <p><strong>课程子类别ID:</strong> <span th:text="${course.couTypeId}"></span></p>
        <p><strong>课程父类别ID:</strong> <span th:text="${course.couParTypeId}"></span></p>
        <p><strong>课程价格:</strong> <span th:text="${course.couPrice}"></span></p>
        <p><strong>章节数:</strong> <span th:text="${course.couCataNum}"></span></p>
        <p><strong>收藏数:</strong> <span id="couCollNum" th:text="${course.couCollNum}"></span></p>
        <p><strong>点赞数:</strong> <span id="couLikeNum" th:text="${course.couLikeNum}"></span></p>
        <p><strong>分享数:</strong> <span th:text="${course.couShareNum}"></span></p>
        <p><strong>点击量:</strong> <span th:text="${course.clicks}"></span></p>
        <p><strong>购买量:</strong> <span th:text="${course.purchase}"></span></p>
        <p><strong>创建时间:</strong> <span th:text="${#temporals.format(course.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span></p>
        <p><strong>更新时间:</strong> <span th:text="${#temporals.format(course.updateTime, 'yyyy-MM-dd HH:mm:ss')}"></span></p>
        <p>
          <strong>平均评分:</strong>
          <span th:if="${averageRating != null and averageRating > 0}" th:text="${#numbers.formatDecimal(averageRating, 1, 1)} + ' / 5'"></span>
          <span th:unless="${averageRating != null and averageRating > 0}">暂无评分</span>
        </p>

        <div class="course-intro">
          <p><strong>课程介绍:</strong></p>
          <p th:text="${course.couIntroduction}"></p>
        </div>

        <div class="course-actions" th:if="${loggedInUser != null and loggedInUser.role == 'STUDENT'}">
          <button id="likeButton" class="btn-like">点赞课程</button>
          <button id="collectButton" class="btn-collect">收藏课程</button>
        </div>
      </div>

      <div class="course-image-section">
        <p><strong>课程封面:</strong></p>
        <img th:if="${course.couPic != null and !course.couPic.isEmpty()}"
             th:src="${course.couPic}" alt="课程封面"
             class="course-image"
             onerror="this.onerror=null;this.src='/images/default-course.jpg';">
        <div th:unless="${course.couPic != null and !course.couPic.isEmpty()}"
             class="course-card-image placeholder" style="height: 200px; width: 100%; display: flex; justify-content: center; align-items: center; background-color: #f0f0f0; color: #888;">
          暂无封面图片
        </div>
      </div>
    </div>

    <div class="chapters-section">
      <h2>
        课程章节
        <a th:if="${loggedInUser != null and loggedInUser.role == 'TEACHER'}"
           th:href="@{/chapter/create/{courseId}(courseId=${course.id})}" class="btn btn-primary btn-sm">添加新章节</a>
      </h2>

      <table th:if="${!#lists.isEmpty(chapters)}">
        <thead>
        <tr>
          <th>章节序号</th>
          <th>章节名称</th>
          <th>章节地址</th>
          <th>章节时长 (秒)</th>
          <th>创建日期</th>
          <th th:if="${loggedInUser != null and loggedInUser.role == 'TEACHER'}">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="chapter : ${chapters}">
          <td th:text="${chapter.chapterOrder}"></td>
          <td th:text="${chapter.chapterName}"></td>
          <td>
            <a href="#" class="btn btn-secondary btn-sm play-video-link"
               th:if="${chapter.chapterUrl != null and !chapter.chapterUrl.isEmpty()}"
               th:data-video-url="${chapter.chapterUrl}">
              播放视频
            </a>
            <span th:unless="${chapter.chapterUrl != null and !chapter.chapterUrl.isEmpty()}" class="no-video-text">暂无视频</span>
          </td>
          <td th:text="${chapter.chapterDuration}"></td>
          <td th:text="${#temporals.format(chapter.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
          <td class="actions-column" th:if="${loggedInUser != null and loggedInUser.role == 'TEACHER'}">
            <button class="btn btn-secondary btn-sm"
                    onclick="openEditChapterModal(
                                            this.getAttribute('data-chapter-id'),
                                            this.getAttribute('data-chapter-name'),
                                            this.getAttribute('data-chapter-url'),
                                            this.getAttribute('data-chapter-duration'),
                                            this.getAttribute('data-chapter-order')
                                        )"
                    th:attr="data-chapter-id=${chapter.id},
                                                 data-chapter-name=${chapter.chapterName},
                                                 data-chapter-url=${chapter.chapterUrl},
                                                 data-chapter-duration=${chapter.chapterDuration},
                                                 data-chapter-order=${chapter.chapterOrder}">编辑</button>

            <form th:action="@{/chapter/delete/{id}(id=${chapter.id})}" method="post" style="display: inline;">
              <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('确定要删除这个章节吗？');">删除</button>
            </form>
          </td>
        </tr>
        </tbody>
      </table>
      <div th:unless="${!#lists.isEmpty(chapters)}" class="no-chapters-message">
        <p>该课程暂无章节。</p>
      </div>
    </div>

    <div class="comments-section">
      <h2>课程评论</h2>
      <div th:if="${!#lists.isEmpty(comments)}">
        <div th:each="comment : ${comments}" class="comment-item">
          <div class="comment-meta">
            <div>
              <strong><span th:text="${comment.studentName}">学生姓名占位符</span></strong>
              于 <span th:text="${#temporals.format(comment.createTime, 'yyyy-MM-dd HH:mm')}">评论时间占位符</span> 评论
            </div>
            <div class="comment-rating">
              评分: <span th:text="${comment.rating}"></span> / 5
            </div>
          </div>
          <p><strong>评论内容:</strong> <span th:text="${comment.content}">评论内容</span></p>
        </div>
      </div>
      <div th:unless="${!#lists.isEmpty(comments)}" class="no-comments-message">
        <p>该课程暂无评论，成为第一个评论者吧！</p>
      </div>
    </div>

  </div>
</div>

<div th:if="${loggedInUser != null and loggedInUser.role == 'STUDENT'}" class="comment-form-section">
  <h2>发表评论</h2>
  <form th:action="@{/course/detail/{courseId}/addComment(courseId=${course.id})}" th:object="${newComment}" method="post" class="comment-form">
    <div class="form-group">
      <label for="commentContent">您的评论:</label>
      <textarea id="commentContent" th:field="*{content}" rows="5" required></textarea> </div>
    <div class="form-group">
      <label for="rating">评分 (1-5):</label>
      <select id="rating" th:field="*{rating}" required>
        <option value="">请选择评分</option>
        <option value="1">1 星</option>
        <option value="2">2 星</option>
        <option value="3">3 星</option>
        <option value="4">4 星</option>
        <option value="5">5 星</option>
      </select>
    </div>
    <div class="form-actions">
      <button type="submit" class="btn btn-primary">提交评论</button>
    </div>
  </form>
</div>

<div style="margin-top: 20px;" th:if="${loggedInUser != null and loggedInUser.role == 'TEACHER'}">
  <a th:href="@{/course/manage}" class="btn btn-secondary">返回课程管理</a>
</div>
<div style="margin-top: 20px;" th:if="${loggedInUser != null and loggedInUser.role == 'STUDENT'}">
  <a th:href="@{/student/courses/browse}" class="btn btn-secondary">返回课程列表</a>
</div>


<div id="editChapterModal" class="modal">
  <div class="modal-content">
    <span class="close-button" onclick="closeEditChapterModal()">&times;</span>
    <h2>编辑章节</h2>
    <form id="editChapterForm" th:action="@{/chapter/edit}" method="post">
      <input type="hidden" id="editChapterId" name="id">
      <input type="hidden" id="editChapterCouId" name="couId" th:value="${course.id}">
      <div class="form-group">
        <label for="editChapterName">章节名称:</label>
        <input type="text" id="editChapterName" name="chapterName" required>
      </div>
      <div class="form-group">
        <label for="editChapterDuration">章节时长 (秒):</label>
        <input type="number" id="editChapterDuration" name="chapterDuration" min="0">
      </div>
      <div class="form-group">
        <label for="editChapterOrder">排列序号:</label>
        <input type="number" id="editChapterOrder" name="chapterOrder" required>
      </div>
      <div class="form-actions">
        <button type="button" class="btn btn-secondary" onclick="closeEditChapterModal()">取消</button>
        <button type="submit" class="btn btn-primary">保存修改</button>
      </div>
    </form>
  </div>
</div>

</div>
</div>


<div id="videoModal" class="modal">
  <div class="modal-content">
    <span id="videoModalCloseButton" class="close-button">&times;</span>
    <video id="videoPlayer" controls preload="auto">
      您的浏览器不支持视频播放。
    </video>
  </div>
</div>

<div id="enrollModal" class="modal">
  <div class="modal-content">
    <span id="closeEnrollModalButton" class="close-button">&times;</span>
    <h2>报名线下实践</h2>
    <form id="enrollForm">
      <input type="hidden" id="enrollPracticeId">
      <p><strong>实践标题:</strong> <span id="enrollPracticeTitle"></span></p>
      <p><strong>实践地点:</strong> <span id="enrollPracticeLocation"></span></p>
      <p><strong>实践时间:</strong> <span id="enrollPracticeTime"></span></p>

      <div class="form-group">
        <label for="enrollName">姓名: <span style="color: red;">*</span></label>
        <input type="text" id="enrollName" required>
      </div>
      <div class="form-group">
        <label for="enrollPhone">电话: <span style="color: red;">*</span></label>
        <input type="tel" id="enrollPhone" required>
      </div>
      <div class="form-group">
        <label for="enrollOptionalLocation">实践地点 (可选):</label>
        <input type="text" id="enrollOptionalLocation">
      </div>
      <div class="form-group">
        <label for="enrollOptionalTime">实践时间 (可选):</label>
        <input type="datetime-local" id="enrollOptionalTime">
      </div>
      <div class="form-group">
        <label for="enrollNotes">备注:</label>
        <textarea id="enrollNotes"></textarea>
      </div>

      <div class="form-actions">
        <button type="submit" class="btn btn-primary">提交报名</button>
        <button type="button" class="btn btn-secondary" id="cancelEnrollButton">取消</button>
      </div>
    </form>
  </div>
</div>


<script th:inline="javascript">
  /*<![CDATA[*/
  // 获取课程ID
  // 从Thymeleaf后端注入 course.id，确保页面加载时即可获取
  const courseId = /*[[${course.id}]]*/ 'defaultCourseId';
  const loggedInUserRole = /*[[${loggedInUser != null ? loggedInUser.role : ''}]]*/ '';

  // 获取DOM元素
  const likeButton = document.getElementById('likeButton');
  const collectButton = document.getElementById('collectButton');
  const couLikeNumElem = document.getElementById('couLikeNum');
  const couCollNumElem = document.getElementById('couCollNum');

  const relatedOfflinePracticesList = document.getElementById('relatedOfflinePracticesList');
  const noRelatedPracticesMessage = document.getElementById('noRelatedPracticesMessage');

  const enrollModal = document.getElementById('enrollModal');
  const enrollForm = document.getElementById('enrollForm');
  const enrollPracticeId = document.getElementById('enrollPracticeId');
  const enrollPracticeTitle = document.getElementById('enrollPracticeTitle');
  const enrollPracticeLocation = document.getElementById('enrollPracticeLocation');
  const enrollPracticeTime = document.getElementById('enrollPracticeTime');
  const enrollName = document.getElementById('enrollName');
  const enrollPhone = document.getElementById('enrollPhone');
  const enrollOptionalLocation = document.getElementById('enrollOptionalLocation');
  const enrollOptionalTime = document.getElementById('enrollOptionalTime');
  const enrollNotes = document.getElementById('enrollNotes');
  const closeEnrollModalButton = document.getElementById('closeEnrollModalButton');
  const cancelEnrollButton = document.getElementById('cancelEnrollButton'); // 取消按钮


  // 假设的后端API地址
  // **重要：请根据您的后端实际地址调整此URL**
  const API_BASE_URL = 'http://localhost:8080/';

  // --- 辅助函数：格式化时间 ---
  function formatDateTime(isoString) {
    if (!isoString) return '';
    const date = new Date(isoString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false // 使用24小时制
    });
  }

  // --- 3.2.10.1 点赞课程 (FR-KCHD-1) ---
  // --- 3.2.10.2 收藏课程 (FR-KCHD-2) ---
  if (loggedInUserRole === 'STUDENT') {
    if (likeButton) {
      likeButton.addEventListener('click', async () => {
        try {
          const response = await fetch(`http://localhost:8080/course/api/like/${courseId}`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 'Authorization': 'Bearer YOUR_TOKEN' // 如果需要认证
            }
          });
          const data = await response.json();
          if (response.ok && data.success) {
            alert('点赞成功！');
            // 假设后端返回最新的点赞数或者更新显示
            // couLikeNumElem.textContent = data.newLikeCount || parseInt(couLikeNumElem.textContent) + 1;
            // 简单递增，实际应该从后端获取最新值
            couLikeNumElem.textContent = parseInt(couLikeNumElem.textContent) + 1;
          } else {
            alert(data.message || '点赞失败。');
          }
        } catch (error) {
          console.error('点赞失败:', error);
          alert('点赞失败，请检查网络或稍后再试。');
        }
      });
    }
    if (collectButton) {
      collectButton.addEventListener('click', async () => {
        try {
          const response = await fetch(`http://localhost:8080/course/api/collect/${courseId}`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 'Authorization': 'Bearer YOUR_TOKEN' // 如果需要认证
            }
          });
          const data = await response.json();
          if (response.ok && data.success) {
            alert('收藏成功！');
            // couCollNumElem.textContent = data.newCollectCount || parseInt(couCollNumElem.textContent) + 1;
            couCollNumElem.textContent = parseInt(couCollNumElem.textContent) + 1;
            collectButton.textContent = '已收藏';
            collectButton.classList.add('btn-collected');
            collectButton.disabled = true; // 收藏后禁用按钮
          } else {
            alert(data.message || '收藏失败。');
          }
        } catch (error) {
          console.error('收藏失败:', error);
          alert('收藏失败，请检查网络或稍后再试。');
        }
      });
    }

    // --- 3.2.10.5 报名线下实践 (FR-KCHD-7) ---
    // 加载课程相关的线下实践
    async function loadRelatedOfflinePractices() {
      relatedOfflinePracticesList.innerHTML = ''; // 清空现有列表
      noRelatedPracticesMessage.style.display = 'none';

      try {
        // 假设后端API为 /api/student/courses/{courseId}/offline_practices
        const response = await fetch(`<span class="math-inline">\{API\_BASE\_URL\}/courses/</span>{courseId}/offline_practices`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const practices = await response.json();

        if (practices.length === 0) {
          noRelatedPracticesMessage.style.display = 'block';
          return;
        }

        practices.forEach(practice => {
          const practiceDiv = document.createElement('div');
          practiceDiv.classList.add('offline-practice-item');
          practiceDiv.innerHTML = `
                      <div><strong>实践标题:</strong> ${practice.title}</div>
                      <div><strong>实践地点:</strong> ${practice.location || '待定'}</div>
                      <div><strong>实践时间:</strong> <span class="math-inline">\{practice\.time ? formatDateTime\(practice\.time\) \: '待定'\}</div\>
<button class\="btn\-enroll" onclick\="openEnrollModal\(
'</span>{practice.id}',
                          '<span class="math-inline">\{practice\.title\}',
'</span>{practice.location || ''}',
                          '${practice.time || ''}'
                      )">报名</button>
                  `;
          relatedOfflinePracticesList.appendChild(practiceDiv);
        });
      } catch (error) {
        console.error('加载相关线下实践失败:', error);
        // alert('加载相关线下实践失败，请稍后再试。'); // 暂时不弹窗，以免频繁打扰
      }
    }

    // 打开报名模态框
    function openEnrollModal(practiceId, title, location, time) {
      enrollPracticeId.value = practiceId;
      enrollPracticeTitle.textContent = title;
      enrollPracticeLocation.textContent = location || '待定';
      enrollPracticeTime.textContent = time ? formatDateTime(time) : '待定';

      // 清空表单，并重置可选字段
      enrollName.value = '';
      enrollPhone.value = '';
      enrollOptionalLocation.value = ''; // 如果需要预填，可以从 location 或 time 派生
      enrollOptionalTime.value = '';
      enrollNotes.value = '';

      enrollModal.style.display = 'flex';
    }

    // 提交报名信息
    if (enrollForm) {
      enrollForm.addEventListener('submit', async (event) => {
        event.preventDefault(); // 阻止表单默认提交

        const practiceId = enrollPracticeId.value;
        const name = enrollName.value.trim();
        const phone = enrollPhone.value.trim();
        const optionalLocation = enrollOptionalLocation.value.trim();
        const optionalTime = enrollOptionalTime.value; // datetime-local 返回的是字符串
        const notes = enrollNotes.value.trim();

        // 约束校验
        if (!name || !phone) {
          alert('姓名和电话不能为空！');
          return;
        }
        // 您可以在这里添加电话号码格式验证等更多校验

        const enrollmentData = {
          practiceId: practiceId,
          name: name,
          phone: phone,
          // 如果可选地点和时间为空，发送 null 或空字符串，后端处理
          location: optionalLocation,
          time: optionalTime ? new Date(optionalTime).toISOString() : null, // 转换为ISO字符串或null
          notes: notes
        };

        try {
          // 假设后端API为 /api/student/offline_practices/enroll
          const response = await fetch(`${API_BASE_URL}/offline_practices/enroll`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 'Authorization': 'Bearer YOUR_TOKEN'
            },
            body: JSON.stringify(enrollmentData)
          });

          const data = await response.json();
          if (response.ok && data.success) {
            alert('报名成功！');
            enrollModal.style.display = 'none'; // 关闭模态框
            loadRelatedOfflinePractices(); // 重新加载列表，可能需要显示已报名状态
          } else {
            alert(data.message || '报名失败。');
          }
        } catch (error) {
          console.error('报名失败:', error);
          alert('报名失败，请检查网络或稍后再试。');
        }
      });
    }

    // 关闭报名模态框
    if (closeEnrollModalButton) {
      closeEnrollModalButton.addEventListener('click', () => {
        enrollModal.style.display = 'none';
      });
    }
    if (cancelEnrollButton) {
      cancelEnrollButton.addEventListener('click', () => {
        enrollModal.style.display = 'none';
      });
    }
    // 点击模态框外部区域时关闭
    if (enrollModal) {
      enrollModal.addEventListener('click', (event) => {
        if (event.target === enrollModal) {
          enrollModal.style.display = 'none';
        }
      });
    }
  }


  // Get the modal for chapter editing (id: editChapterModal)
  var editChapterModal = document.getElementById("editChapterModal");

  // Function to open the chapter edit modal and populate data
  function openEditChapterModal(id, name, url, duration, order) {
    document.getElementById("editChapterId").value = id;
    document.getElementById("editChapterName").value = name;
    document.getElementById("editChapterDuration").value = duration;
    document.getElementById("editChapterOrder").value = order;
    editChapterModal.style.display = "flex"; // Use flex to center the modal
  }

  // Function to close the chapter edit modal
  function closeEditChapterModal() {
    editChapterModal.style.display = "none";
  }

  // When the user clicks anywhere outside of the chapter edit modal, close it
  window.onclick = function(event) {
    if (event.target == editChapterModal) { // 确保只对 editChapterModal 生效
      editChapterModal.style.display = "none";
    }
  }

  // 获取视频播放模态框元素
  const videoModal = document.getElementById('videoModal');
  const videoPlayer = document.getElementById('videoPlayer');
  const videoModalCloseButton = document.getElementById('videoModalCloseButton');

  const playVideoLinks = document.querySelectorAll('.play-video-link'); // 获取所有播放视频链接

  // 点击播放视频链接时
  playVideoLinks.forEach(link => {
    link.addEventListener('click', function(event) {
      event.preventDefault(); // 阻止a标签的默认跳转行为
      const videoUrl = this.getAttribute('data-video-url'); // 获取视频URL

      if (videoUrl) {
        videoPlayer.src = videoUrl; // 设置视频源
        videoModal.style.display = 'flex'; // 显示模态框 (使用 flexbox 居中)
        videoPlayer.play(); // 播放视频
      } else {
        alert('视频URL未指定！'); // 或其他错误处理
      }
    });
  });

  // 点击视频模态框关闭按钮时
  if (videoModalCloseButton) { // 添加一个检查以确保元素存在
    videoModalCloseButton.addEventListener('click', function() {
      videoModal.style.display = 'none'; // 隐藏模态框
      videoPlayer.pause(); // 暂停视频
      videoPlayer.currentTime = 0; // 视频回到开头
    });
  }


  // 点击视频模态框外部区域时关闭模态框
  videoModal.addEventListener('click', function(event) {
    if (event.target === videoModal) {
      videoModal.style.display = 'none';
      videoPlayer.pause();
      videoPlayer.currentTime = 0;
    }
  });

  // 监听 ESC 键关闭视频模态框
  document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
      if (videoModal.style.display === 'flex') {
        videoModal.style.display = 'none';
        videoPlayer.pause();
        videoPlayer.currentTime = 0;
      }
    }
  });

  // 页面加载时执行
  document.addEventListener('DOMContentLoaded', () => {
    // 检查 courseId 是否有效
    if (!courseId || courseId === 'defaultCourseId') {
      console.error('课程ID未定义或无效，部分功能可能无法正常工作。');
      // alert('课程ID未定义，请检查页面配置。');
      return; // 阻止后续依赖 courseId 的操作
    }

    // 如果是学生角色，加载相关线下实践
    if (loggedInUserRole === 'STUDENT') {
      loadRelatedOfflinePractices();
    }
    // 其他初始化功能（如播放视频等，这些在现有代码中已在 DOMContentLoaded 外部）
  });
  /*]]>*/
</script>
</body>
</html>